package org.lab.mtga.core;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import net.sf.flatpack.DataSet;
import net.sf.flatpack.DefaultParserFactory;
import net.sf.flatpack.Parser;

import org.lab.mtga.core.guice.MTGACoreModule;
import org.lab.mtga.core.jpa.EntityManagerProvider;
import org.lab.mtga.core.model.Card;

import com.google.inject.Guice;
import com.google.inject.Injector;

public class MTGABootstrap implements Runnable {

	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new MTGACoreModule());
		injector.getInstance(MTGABootstrap.class).run();
	}

	@Inject
	private EntityManagerProvider entityManagerProvider;

	@Override
	public void run() {
		List<Card> localCards = readLocalCards();
		EntityManager entityManager = entityManagerProvider.get();
		entityManager.getTransaction().begin();
		for (Card card : localCards) {
			entityManager.persist(card);
		}
		entityManager.getTransaction().commit();
	}

	private List<Card> readLocalCards() {
		try {
			InputStream inputStream = getClass().getResourceAsStream("/database/cards.csv");
			Reader reader = new InputStreamReader(inputStream, "UTF8");
			Parser parser = DefaultParserFactory.getInstance().newDelimitedParser(reader, ',', '"');
			DataSet dataSet = parser.parse();
			List<Card> cards = new ArrayList<Card>();
			while (dataSet.next()) {
				Card card = new Card();
				card.setName(dataSet.getString("NAME"));
				cards.add(card);
			}
			return cards;
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

}
